//路由权限交谈逻辑
import checkAccess from "../access/checkAccess";
import ACCESS_ENUM from "@/access/accessEnum";
import router from "@/router";
import { useLoginUserStore } from "@/stores/useLoginUserstore";
import { message } from 'ant-design-vue'

//前置路由守卫，跳转路由前触发
router.beforeEach(async (to, from, next) => {
  const userStore = useLoginUserStore()
  let loginUser = userStore.loginUser;

  if (!loginUser || !loginUser.userRole) {
    await userStore.fetchLoginUser();
    await userStore.fetchUserInterviewRole()
    loginUser = userStore.loginUser;
  }

  const loginUserAccess = loginUser?.userRole ?? ACCESS_ENUM.NOT_LOGIN;
  const needAccess = (to.meta?.access as string) ?? ACCESS_ENUM.NOT_LOGIN;

  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    if (loginUserAccess === ACCESS_ENUM.NOT_LOGIN) {
      console.log('用户没有登录')

      // 根据路由前缀确定登录页面类型
      let loginPath = '/user/login'; // 默认用户登录页

      if (to.path.startsWith('/admin')) {
        loginPath = '/admin/login'; // 管理员登录页
      } else if (to.path.startsWith('/recruiter')) {
        loginPath = '/recruiter/login'; // 招聘者登录页
      }

      // 跳转到对应的登录页面，并携带重定向地址
      next(`${loginPath}?redirect=${encodeURIComponent(to.fullPath)}`);
      return;
    }

    if (!checkAccess(loginUser, needAccess)) {
      message.error("无权限");
      next("/");
      return;
    }
  }

  next();
});
